<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Repositories\Contracts\PermissionRepositoryInterface;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class PermissionController extends Controller
{

  private $permissionRepository;


  public function __construct(PermissionRepositoryInterface $permissionRepository)
  {
    $this->permissionRepository = $permissionRepository;
  }

  /**
   * 管理员，对用户进行修改，新增操作
   *
   * @param Request $request
   *
   * @return \Illuminate\Http\JsonResponse
   */
  public function save(Request $request)
  {

    $id = $request->input("id", 0);

    $data = $request->only('name', 'guard_name');
    $this->validation($request, $id);
    $data = $this->permissionRepository->save($data, $id);
    return $this->result($data != null, $data);
  }


  public function lists()
  {
    $result = $this->permissionRepository->paginate();
    return $this->result(true, $result);
  }

  public function all()
  {
    $result = $this->permissionRepository->all(['id', 'name']);
    return $this->result(true, $result);
  }

  public function remove($id = 0)
  {

    return $this->result($this->permissionRepository->delete($id));
  }

  protected function validation($request, $id)
  {

    $permission = [
      'name' => ['required', 'string', 'max:255'],
      'guard_name' => ['required', 'string'],
    ];
    if ($id < 1) {
      // 新用户做唯一性检测
      $permission['name'][] = "unique:permissions,name";
    } else {
      $permission['name'][] = Rule::unique('permissions')->ignore($id);
    }

    $this->validateWith($permission, $request);
  }
}
